package services

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/xuri/excelize/v2"
	"hysx/models"
	"hysx/repositories"
	"mime/multipart"
	"time"
)

// {{.StructName}}Service {{.TableComment}}Service层
type {{.StructName}}Service struct {
	Repository *repositories.{{.StructName}}Repository
}

// New{{.StructName}}Service 创建Service层
func New{{.StructName}}Service(repo *repositories.{{.StructName}}Repository) *{{.StructName}}Service {
	return &{{.StructName}}Service{Repository: repo}
}

// Add{{.StructName}} 添加{{.TableComment}}
func (service *{{.StructName}}Service) Add{{.StructName}}(ctx context.Context, {{.TabName}} *models.{{.StructName}}) {
	now := models.MyTime(time.Now())
	{{.TabName}}.CreateTime = &now
	{{.TabName}}.UpdateTime = &now
	service.Repository.Insert{{.StructName}}(ctx, {{.TabName}})
}

// Remove{{.StructName}} 删除{{.TableComment}}
func (service *{{.StructName}}Service) Remove{{.StructName}}(ctx context.Context, {{.TabName}}ID *int) {
	service.Repository.Delete{{.StructName}}(ctx, {{.TabName}}ID)
}

// Modify{{.StructName}} 修改{{.TableComment}}
func (service *{{.StructName}}Service) Modify{{.StructName}}(ctx context.Context, {{.TabName}} *models.{{.StructName}}) {
	now := models.MyTime(time.Now())
	{{.TabName}}.UpdateTime = &now
	service.Repository.Update{{.StructName}}(ctx, {{.TabName}})
}

// Get{{.StructName}}List 获取{{.TableComment}}列表
func (service *{{.StructName}}Service) Get{{.StructName}}List(ctx context.Context, {{.TabName}} *models.{{.StructName}}, pageSize, PageNum int) repositories.PageInfo {
	return service.Repository.Select{{.StructName}}List(ctx, {{.TabName}}, PageNum, pageSize)
}

// Get{{.StructName}}ById 通过ID查询{{.TableComment}}
func (service *{{.StructName}}Service) Get{{.StructName}}ById(ctx context.Context, {{.TabName}}Id *int) models.{{.StructName}} {
	return service.Repository.Select{{.StructName}}ByID(ctx, {{.TabName}}Id)
}

// Import{{.StructName}} 批量导入{{.TableComment}}
func (service *{{.StructName}}Service) Import{{.StructName}}(ctx context.Context, file *multipart.FileHeader) {
	var list = parseExcel(file, models.{{.StructName}}{}, "{{.TableComment}}导入模板").([]*models.{{.StructName}})
	data, _ := json.Marshal(*list[0])
	fmt.Println("长度：", len(list), list[0])
	fmt.Println(string(data))
	service.Repository.Import{{.StructName}}(ctx, list)
}

// Export{{.StructName}} 批量导出{{.TableComment}}
func (service *{{.StructName}}Service) Export{{.StructName}}(ctx context.Context, ids []string) *excelize.File {
	list := service.Repository.Export{{.StructName}}(ctx, ids)
	return generatorExcel(&models.{{.StructName}}{}, list, "{{.TableComment}}数据")
}

// DownloadImportTemplate 下载导出模板{{.TableComment}}
func (service *{{.StructName}}Service) DownloadImportTemplate() *excelize.File {
	return generatorExcel(&models.{{.StructName}}{}, nil, "{{.TableComment}}导入模板")
}
